﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Xna.Framework.Graphics;
using System.ComponentModel;
using System.Windows.Interop;
using System.Windows.Threading;
using System.Windows.Forms.Integration;

namespace Pavilion.DesignerTool
{
    public partial class XnaView : UserControl
    {
        private IXnaComponent xnaComponent;
        private XnaTimer xnaTimer;
        public XnaWindowsFormPanel XnaWinFormsPanel { get; private set; }

        public XnaView()
        {
            InitializeComponent();

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                xnaTimer = new XnaTimer();
                XnaWinFormsPanel = new XnaWindowsFormPanel();
            }

            WindowsFormsHost.EnableWindowsFormsInterop();

            formsHost.Child = XnaWinFormsPanel;
            this.IsVisibleChanged += new DependencyPropertyChangedEventHandler(XnaView_IsVisibleChanged);
        }

        void XnaView_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                if (IsVisible)
                    System.Windows.Media.CompositionTarget.Rendering += CompositionTarget_Rendering;
                else
                    System.Windows.Media.CompositionTarget.Rendering -= CompositionTarget_Rendering;
            }
        }

        public IXnaComponent XnaComponent
        {
            get { return xnaComponent; }
            set
            {
                if (xnaComponent == value)
                    return;

                xnaComponent = value;

                if (xnaComponent != null && !DesignerProperties.GetIsInDesignMode(this))
                    XnaComponent.Load(GraphicsDeviceService.Instance.GraphicsDevice, GraphicsDeviceService.Instance.Services);
            }
        }

        private void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            if (XnaComponent == null || this.Visibility != Visibility.Visible || DrawManager.Instance.IsDrawing)
                return;

            xnaTimer.Update();
            XnaComponent.Update(xnaTimer.GameTime);

            if (XnaWinFormsPanel.BeginDraw())
            {
                XnaComponent.Draw();
                XnaWinFormsPanel.EndDraw();
            }
        }

        private void XnaView_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (XnaComponent == null)
                return;

            XnaComponent.SizeChanged(e.NewSize.Width, e.NewSize.Height);
        }
    }
}
